# encoding = 'utf8' 
import sys
import urllib
import string

try:
    import xbmc, xbmcgui, xbmcplugin
    WorkWithXBMC = True
except:
    WorkWithXBMC = False
    
################################################################################################
def safeTranslatePath(path):     
    newPath = ""
    print "path=%s" % path
    try:
        import xbmc    
        newPath = xbmc.translatePath( path )
        print "newPath=%s" % newPath        
    except:    
        newPath = path
    
    print "safeTranslatePath=%s" % newPath
    return newPath

################################################################################################

        
class XbmcHandler:                  
    def __init__(self,):
        self.workWithXBMC = WorkWithXBMC        
        self.handle = int(sys.argv[1])
        if(self.workWithXBMC):
            self.SORT_METHOD_LABEL = xbmcplugin.SORT_METHOD_LABEL
        else: self.SORT_METHOD_LABEL = ""
    
    ###############################################################################################
    def addItem(self, 
                pluginOnlineUrl, 
                userName,
                password,               
                name, 
                url,
                urlParams,
                iconimage='DefaultFolder.png', 
                elementId='', 
                summary='', 
                fanart='',
                isFolder=True, 
                totalItems=1,
                trailer=""):
        if(not self.workWithXBMC): return
        
        fullUrl = sys.argv[0] + '?' + url
        liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo(type="Video", infoLabels={ 
                                              "Title":      urllib.unquote(name), 
                                              "Plot":       urllib.unquote(summary),
                                              "trailer" :   urllib.unquote(r"http://www.youtube.com/watch?v=hbLgszfXTAY") 
                                              }) 
        if not fanart=='':
            liz.setProperty("Fanart_Image", fanart)   
        liz.setProperty('IsPlayable', 'true')
        
        commands = self.CreateContextMenu(pluginOnlineUrl=pluginOnlineUrl, urlParams=urlParams, userName=userName, password=password)
        
        liz.addContextMenuItems( commands )      
       
        ok=xbmcplugin.addDirectoryItem(handle=self.handle,url=fullUrl,listitem=liz,isFolder=isFolder, totalItems=totalItems)
        return ok
      
    ################################################################################################
    def endOfDirectory(self, succeeded=True):
        if(not self.workWithXBMC): return
        xbmcplugin.endOfDirectory(handle=self.handle, succeeded=succeeded)
        
    ################################################################################################   
    def addMovieDirectoryItem(self, url, listitem):
        if(not self.workWithXBMC): return
        return xbmcplugin.addDirectoryItem(handle=self.handle, url=url, listitem=listitem, isFolder=True)
    
    def addDirectoryItem(self, url, listitem, isFolder=True, totalItems=10):
        if(not self.workWithXBMC): return    
        #print("addDirectoryItem: %s" % url)
        return xbmcplugin.addDirectoryItem(handle=self.handle, url=url, listitem=listitem, isFolder=isFolder, totalItems=totalItems)
    
    ################################################################################################
    def addTitleDirectoryItem(self, name, url, isFolder=True, totalItems=10):
        if(not self.workWithXBMC): return    
        listitem = xbmcgui.ListItem(name)
        return xbmcplugin.addDirectoryItem(handle=self.handle, url=url, listitem=listitem, isFolder=isFolder, totalItems=totalItems)
    
    ################################################################################################
    def addMenuItems(self, menuItesmList):
        if(not self.workWithXBMC): return
        for i in range(0, 5):
            name = "%s Item %d" % (FIRST_SUBMENU, i)
            menuItesmList.append(name)
            
        xbmcplugin.endOfDirectory(handle=self.handle, succeeded=True)
    
    ################################################################################################  
    def translatePath(self, path):
        if(not self.workWithXBMC): return path
        return xbmc.translatePath(path)       
            
    ################################################################################################
    def ListItem(self, name):
        if(not self.workWithXBMC): return
        return xbmcgui.ListItem(name)
    
    ################################################################################################
    def ListItemEx(self, label, iconImage, thumbnailImage):
        if(not self.workWithXBMC): return
        return xbmcgui.ListItem(label=label, label2=label, iconImage=iconImage, thumbnailImage=thumbnailImage)
    
    
    def addVideoLink(name, url, mode, iconimage='DefaultFolder.png', summary = ''):
        u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + name
        liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
        liz.setInfo(type="Video", infoLabels={ "Title": urllib.unquote(name), "Plot": urllib.unquote(summary)})    
        liz.setProperty('IsPlayable', 'true')
        ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=False)
        return ok
    
    ################################################################################################
    def PlayVideo(self, movie_link, name, iconImage=""):
        if(not self.workWithXBMC): return
        
        listItem = xbmcgui.ListItem(label=str(name), label2=str(name), iconImage="DefaultVideo.png", thumbnailImage="DefaultVideo.png")
        listItem.setInfo( type="Video", infoLabels={ "title": str(name) } )
        listItem.setProperty('IsPlayable', 'true')
        xbmcplugin.addDirectoryItem(handle=self.handle,url=str(movie_link), listitem=listItem, totalItems=1)
        #xbmcplugin.setResolvedUrl(self.handle, True, listItem)       
        
    ################################################################################################
    def OpenKeyboard(self, defaultSearchString, SearchTitle):
        if(not self.workWithXBMC): return
        kb = xbmc.Keyboard(defaultSearchString, SearchTitle, False)
        kb.doModal()
        if (kb.isConfirmed()):
            search = kb.getText()
            return search
        return ''
        
    ################################################################################################    
    def AddVideobb(self, url, name):
        if(not self.workWithXBMC): return
        listItem = xbmcgui.ListItem('Standard Megavideo File', 'DefaultFolder.png', 'DefaultFolder.png', path=url)
        listItem.setInfo(type='Video', infoLabels={ "Title": urllib.unquote(name)})
        listItem.setProperty('IsPlayable', 'true')
        xbmcplugin.setResolvedUrl(handle=self.handle, succeeded=True, listitem=listItem)

    ################################################################################################
    def GetFromSetting(self, parameterName, defaultValue=""):
        if(not self.workWithXBMC): return defaultValue        
        return xbmcplugin.getSetting(self.handle, parameterName)
    
    ################################################################################################
    def ShowMessageBox(self, caption, message):
        if(not self.workWithXBMC): return
        dialog = xbmcgui.Dialog()
        result = dialog.ok(caption, message)
        print "ShowMessageBox result = [%s]" % result     
    
    def PlaySwfPlayerItem(self, name, playerUrl, playerParams, link):
        if(not self.workWithXBMC): return
        item = xbmcgui.ListItem(name) 
        item.setProperty("SWFPlayer", playerUrl) 
        #item.setProperty("PlayPath", "zonein")
        for paramName, paramValue in playerParams:
            item.setProperty(paramName, paramValue) 
        xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(link, item)
            
    
    def CreateContextMenu(self, pluginOnlineUrl, urlParams, userName, password):        
        MOVIES_MODE = "1"
        SERIES_MODE = "2"
        
        commands = []
        pluginMode = 0
        videoId = 0
        seriesId = 0
        seasonNumber = 0
        
        if urlParams.__contains__('PluginMode'):
            pluginMode = str(urlParams['PluginMode'])
            
        if urlParams.__contains__('VideoId'):
            videoId = int( urlParams['VideoId'])
        
        if urlParams.__contains__('SeriesId'):
            seriesId = int( urlParams['SeriesId'])    
                
        print pluginMode
        print videoId
        print seriesId
        print userName
        print password
        
        print (pluginMode == SERIES_MODE)
        
        isTvShow = (pluginMode == SERIES_MODE)
        isMovie = (pluginMode == MOVIES_MODE)
        
        if(isTvShow and seriesId == 0 and videoId == 0):
            return commands       
        
        elif(isMovie and videoId == 0):
            return commands
    
        if(isTvShow):
            commandParams = "PluginMode=%s userName=%s password=%s videoId=%s seriesId=%s" % ( str(pluginMode), userName, password, str(videoId), str(seriesId) )
            addCommandName = urllib.unquote_plus("%D7%94%D7%95%D7%A1%D7%A3%20%D7%9C%D7%A1%D7%93%D7%A8%D7%95%D7%AA%20%D7%A9%D7%9C%D7%99")
            removeCommandName = urllib.unquote_plus("%D7%94%D7%A1%D7%A8%20%D7%9E%D7%94%D7%A1%D7%93%D7%A8%D7%95%D7%AA%20%D7%A9%D7%9C%D7%99")
                        
        elif(isMovie):
            commandParams = "PluginMode=%s userName=%s password=%s videoId=%s" % ( str(pluginMode), userName, password, str(videoId) )
            addCommandName = urllib.unquote_plus("%D7%94%D7%95%D7%A1%D7%A3%20%D7%9C%D7%A1%D7%A8%D7%98%D7%99%D7%9D%20%D7%A9%D7%9C%D7%99")
            removeCommandName = urllib.unquote_plus("%D7%94%D7%A1%D7%A8%20%D7%9E%D7%94%D7%A1%D7%A8%D7%98%D7%99%D7%9D%20%D7%A9%D7%9C%D7%99")
        else:
            return commands
        
        argsRemove  = "Remove %s" % commandParams 
        argsAdd     = "Add %s" % commandParams
        
        pluginPath = safeTranslatePath("special://home/")
        print "pluginPath: %s" % pluginPath
        
        runnerRemove = "XBMC.RunScript(" + pluginPath + "addons/plugin.all.in.one.plugin/SitesParsers/ContextMenuHanler.py, " + pluginOnlineUrl + " " + argsRemove + ")"
        runnerAdd = "XBMC.RunScript(" + pluginPath + "addons/plugin.all.in.one.plugin/SitesParsers/ContextMenuHanler.py, " + pluginOnlineUrl + " " + argsAdd + ")"
    
        print runnerAdd
        
        commands.append((addCommandName, runnerAdd, ))            
        commands.append(( removeCommandName, runnerRemove, ))
    
        return commands
